import { createTool } from '@mastra/core/tools';
import { z } from 'zod';

/**
 * 评分工具
 * 专门处理推理结果评估、反馈生成、学习建议等评分相关功能
 */
export const scoringTool = createTool({
  id: 'scoring',
  description: '评分工具，负责处理推理评估的所有核心逻辑',
  inputSchema: z.object({
    action: z.enum([
      'evaluate_deduction',
      'analyze_evidence_use',
      'assess_investigation',
      'generate_feedback',
      'suggest_improvements',
      'full_evaluation'
    ]).describe('要执行的评估操作类型'),
    
    // 推理结果
    deduction: z.object({
      culpritId: z.string(),
      reasoning: z.string(),
      evidence: z.array(z.string()),
      confidence: z.number()
    }).describe('玩家的推理结果'),
    
    // 正确答案
    correctAnswer: z.object({
      culpritId: z.string(),
      culpritName: z.string().optional(),
      correctReasoning: z.string().optional()
    }).describe('正确答案信息'),
    
    // 案件数据
    caseData: z.object({
      case: z.object({
        title: z.string(),
        description: z.string(),
        difficulty: z.string().optional()
      }),
      suspects: z.array(z.object({
        id: z.string(),
        name: z.string(),
        suspicionLevel: z.number().optional()
      })).optional(),
      allClues: z.array(z.object({
        id: z.string(),
        description: z.string(),
        importance: z.number(),
        type: z.string()
      })).optional()
    }).describe('案件相关数据'),
    
    // 游戏历史
    gameHistory: z.object({
      discoveredClues: z.array(z.any()),
      conversationHistory: z.array(z.any()),
      timeUsed: z.number(),
      totalTime: z.number(),
      suspectInteractions: z.record(z.number()).optional()
    }).describe('游戏过程历史'),
    
    // 评估参数
    evaluationCriteria: z.object({
      accuracyWeight: z.number().optional(),
      evidenceWeight: z.number().optional(),
      processWeight: z.number().optional(),
      efficiencyWeight: z.number().optional()
    }).optional().describe('评估标准权重'),
    
    // 其他参数
    playerProfile: z.object({
      experience: z.string().optional(),
      previousScores: z.array(z.number()).optional(),
      strengths: z.array(z.string()).optional(),
      weaknesses: z.array(z.string()).optional()
    }).optional().describe('玩家档案信息')
  }),
  outputSchema: z.object({
    success: z.boolean().describe('评估是否成功'),
    isCorrect: z.boolean().describe('推理结果是否正确'),
    totalScore: z.number().describe('总分 (0-100)'),
    grade: z.string().describe('等级评定 (A/B/C/D/F)'),
    detailedScores: z.object({
      accuracy: z.number(),
      evidenceUse: z.number(),
      investigation: z.number(),
      efficiency: z.number()
    }).describe('各维度详细得分'),
    feedback: z.string().describe('详细反馈'),
    strengths: z.array(z.string()).describe('表现优秀的方面'),
    improvements: z.array(z.string()).describe('需要改进的方面'),
    suggestions: z.array(z.string()).describe('具体改进建议'),
    learningPlan: z.object({
      focus: z.string(),
      exercises: z.array(z.string()),
      resources: z.array(z.string())
    }).optional().describe('个性化学习计划'),
    comparison: z.object({
      averageScore: z.number(),
      percentile: z.number(),
      improvement: z.number()
    }).optional().describe('与平均水平的比较'),
    message: z.string().describe('操作结果消息')
  }),
  execute: async ({ context }) => {
    const { 
      action, 
      deduction, 
      correctAnswer, 
      caseData, 
      gameHistory,
      evaluationCriteria = {},
      playerProfile = {}
    } = context;
    
    try {
      console.log(`评分工具执行操作: ${action}`);
      
      switch (action) {
        case 'evaluate_deduction':
          return await evaluateDeductionAccuracy(deduction, correctAnswer, caseData);
          
        case 'analyze_evidence_use':
          return await analyzeEvidenceUsage(deduction, gameHistory, caseData);
          
        case 'assess_investigation':
          return await assessInvestigationProcess(gameHistory, caseData);
          
        case 'generate_feedback':
          return await generateDetailedFeedback(deduction, correctAnswer, gameHistory, caseData);
          
        case 'suggest_improvements':
          return await suggestImprovements(deduction, gameHistory, playerProfile);
          
        case 'full_evaluation':
          return await performFullEvaluation(deduction, correctAnswer, caseData, gameHistory, evaluationCriteria, playerProfile);
          
        default:
          return {
            success: false,
            isCorrect: false,
            totalScore: 0,
            grade: 'F',
            detailedScores: { accuracy: 0, evidenceUse: 0, investigation: 0, efficiency: 0 },
            feedback: '未知的评估操作类型',
            strengths: [],
            improvements: [],
            suggestions: [],
            message: `未知的操作类型: ${action}`
          };
      }
    } catch (error) {
      console.error(`评分工具操作失败 [${action}]:`, error);
      return {
        success: false,
        isCorrect: false,
        totalScore: 0,
        grade: 'F',
        detailedScores: { accuracy: 0, evidenceUse: 0, investigation: 0, efficiency: 0 },
        feedback: '评估过程中出现错误，请稍后重试',
        strengths: [],
        improvements: ['系统错误，建议重新尝试'],
        suggestions: ['检查网络连接', '稍后重试'],
        message: `操作失败: ${error instanceof Error ? error.message : '未知错误'}`
      };
    }
  },
});

/**
 * 评估推理准确性
 */
async function evaluateDeductionAccuracy(deduction: any, correctAnswer: any, caseData: any) {
  const isCorrect = deduction.culpritId === correctAnswer.culpritId;
  
  // 准确性评分 (0-40分)
  let accuracyScore = 0;
  if (isCorrect) {
    accuracyScore = 40;
    // 根据推理质量调整分数
    if (deduction.reasoning.length > 100) accuracyScore += 5;
    if (deduction.confidence > 80) accuracyScore += 3;
    if (deduction.confidence < 60) accuracyScore -= 2;
  } else {
    // 即使答案错误，也要评估推理过程
    if (deduction.reasoning.length > 50) accuracyScore += 5;
    if (deduction.evidence.length > 2) accuracyScore += 5;
    if (analyzeReasoningLogic(deduction.reasoning)) accuracyScore += 10;
  }
  
  accuracyScore = Math.max(0, Math.min(accuracyScore, 45));
  
  return {
    success: true,
    isCorrect,
    totalScore: accuracyScore,
    grade: getGradeFromScore(accuracyScore),
    detailedScores: { 
      accuracy: accuracyScore, 
      evidenceUse: 0, 
      investigation: 0, 
      efficiency: 0 
    },
    feedback: isCorrect ? 
      '推理结果正确！你成功识别了真凶。' : 
      '推理结果不正确，但你的分析过程有一定价值。',
    strengths: isCorrect ? ['推理准确性高', '结论正确'] : [],
    improvements: isCorrect ? [] : ['推理准确性需要提升', '证据分析需要加强'],
    suggestions: isCorrect ? 
      ['继续保持良好的推理能力'] : 
      ['仔细分析所有证据', '注意逻辑推理的严密性'],
    message: '推理准确性评估完成'
  };
}

/**
 * 分析证据使用情况
 */
async function analyzeEvidenceUsage(deduction: any, gameHistory: any, caseData: any) {
  const { discoveredClues = [], conversationHistory = [] } = gameHistory;
  const { evidence = [] } = deduction;
  
  // 证据使用评分 (0-30分)
  let evidenceScore = 0;
  
  // 证据数量评分
  const evidenceCount = evidence.length;
  evidenceScore += Math.min(evidenceCount * 5, 15);
  
  // 证据质量评分
  const relevantClues = discoveredClues.filter((clue: any) => 
    evidence.some(ev => clue.description.includes(ev) || ev.includes(clue.description))
  );
  evidenceScore += Math.min(relevantClues.length * 3, 10);
  
  // 重要证据使用评分
  const importantClues = relevantClues.filter((clue: any) => clue.importance >= 7);
  evidenceScore += importantClues.length * 2;
  
  // 证据完整性评分
  const totalImportantClues = discoveredClues.filter((clue: any) => clue.importance >= 7).length;
  if (totalImportantClues > 0) {
    const completeness = importantClues.length / totalImportantClues;
    evidenceScore += completeness * 5;
  }
  
  evidenceScore = Math.max(0, Math.min(evidenceScore, 30));
  
  const strengths = [];
  const improvements = [];
  
  if (evidenceCount >= 3) {
    strengths.push('证据收集充分');
  } else {
    improvements.push('需要收集更多支持证据');
  }
  
  if (importantClues.length > 0) {
    strengths.push('使用了关键证据');
  } else {
    improvements.push('需要识别和使用重要证据');
  }
  
  return {
    success: true,
    isCorrect: false, // 这里不评估正确性
    totalScore: evidenceScore,
    grade: getGradeFromScore(evidenceScore * 100 / 30),
    detailedScores: { 
      accuracy: 0, 
      evidenceUse: evidenceScore, 
      investigation: 0, 
      efficiency: 0 
    },
    feedback: `证据使用分析：你使用了${evidenceCount}条证据，其中${importantClues.length}条为重要证据。`,
    strengths,
    improvements,
    suggestions: generateEvidenceSuggestions(evidenceCount, importantClues.length, discoveredClues.length),
    message: '证据使用分析完成'
  };
}

/**
 * 评估调查过程
 */
async function assessInvestigationProcess(gameHistory: any, caseData: any) {
  const { conversationHistory = [], timeUsed, totalTime, suspectInteractions = {} } = gameHistory;
  
  // 调查过程评分 (0-20分)
  let investigationScore = 0;
  
  // 对话深度评分
  const meaningfulConversations = conversationHistory.filter((conv: any) => conv.content.length > 30);
  investigationScore += Math.min(meaningfulConversations.length * 2, 10);
  
  // 嫌疑人覆盖评分
  const interactedSuspects = Object.keys(suspectInteractions).length;
  const totalSuspects = caseData.suspects?.length || 3;
  const coverage = interactedSuspects / totalSuspects;
  investigationScore += coverage * 5;
  
  // 调查系统性评分
  const questionTypes = analyzeQuestionTypes(conversationHistory);
  investigationScore += questionTypes.length * 1;
  
  // 时间管理评分 (0-10分)
  const timeEfficiency = 1 - (timeUsed / totalTime);
  const efficiencyScore = Math.max(0, timeEfficiency * 10);
  
  investigationScore = Math.max(0, Math.min(investigationScore, 20));
  
  const strengths = [];
  const improvements = [];
  
  if (coverage >= 0.8) {
    strengths.push('全面调查所有嫌疑人');
  } else {
    improvements.push('需要与更多嫌疑人对话');
  }
  
  if (meaningfulConversations.length >= 5) {
    strengths.push('对话深入有效');
  } else {
    improvements.push('需要进行更深入的对话');
  }
  
  if (timeEfficiency > 0.3) {
    strengths.push('时间管理良好');
  } else {
    improvements.push('需要提高调查效率');
  }
  
  return {
    success: true,
    isCorrect: false,
    totalScore: investigationScore + efficiencyScore,
    grade: getGradeFromScore((investigationScore + efficiencyScore) * 100 / 30),
    detailedScores: { 
      accuracy: 0, 
      evidenceUse: 0, 
      investigation: investigationScore, 
      efficiency: efficiencyScore 
    },
    feedback: `调查过程评估：进行了${conversationHistory.length}轮对话，与${interactedSuspects}/${totalSuspects}个嫌疑人互动，时间效率${Math.round(timeEfficiency * 100)}%。`,
    strengths,
    improvements,
    suggestions: generateInvestigationSuggestions(coverage, meaningfulConversations.length, timeEfficiency),
    message: '调查过程评估完成'
  };
}

/**
 * 生成详细反馈
 */
async function generateDetailedFeedback(deduction: any, correctAnswer: any, gameHistory: any, caseData: any) {
  const isCorrect = deduction.culpritId === correctAnswer.culpritId;
  const { discoveredClues = [], conversationHistory = [] } = gameHistory;
  
  let feedback = '';
  
  if (isCorrect) {
    feedback += `🎉 恭喜你！你成功找到了真凶 ${correctAnswer.culpritName}！\n\n`;
    feedback += `你的推理过程展现了出色的逻辑思维能力。`;
  } else {
    feedback += `😔 很遗憾，你选择的嫌疑人不是真凶。正确答案是 ${correctAnswer.culpritName}。\n\n`;
    feedback += `虽然结果不正确，但你的调查过程仍然有价值。`;
  }
  
  feedback += `\n\n📊 调查数据统计：\n`;
  feedback += `• 发现线索：${discoveredClues.length} 条\n`;
  feedback += `• 对话轮次：${conversationHistory.length} 次\n`;
  feedback += `• 使用证据：${deduction.evidence.length} 条\n`;
  feedback += `• 信心程度：${deduction.confidence}%\n`;
  
  feedback += `\n💭 推理分析：\n`;
  feedback += `你的推理过程：${deduction.reasoning}\n`;
  
  if (deduction.evidence.length > 0) {
    feedback += `\n🔍 使用的证据：\n`;
    deduction.evidence.forEach((evidence: string, index: number) => {
      feedback += `${index + 1}. ${evidence}\n`;
    });
  }
  
  return {
    success: true,
    isCorrect,
    totalScore: 0, // 这里不计算总分
    grade: 'N/A',
    detailedScores: { accuracy: 0, evidenceUse: 0, investigation: 0, efficiency: 0 },
    feedback,
    strengths: [],
    improvements: [],
    suggestions: [],
    message: '详细反馈生成完成'
  };
}

/**
 * 提供改进建议
 */
async function suggestImprovements(deduction: any, gameHistory: any, playerProfile: any) {
  const suggestions = [];
  const { discoveredClues = [], conversationHistory = [] } = gameHistory;
  const { previousScores = [], weaknesses = [] } = playerProfile;
  
  // 基于当前表现的建议
  if (deduction.evidence.length < 3) {
    suggestions.push('尝试收集更多支持证据来加强你的推理');
  }
  
  if (conversationHistory.length < 5) {
    suggestions.push('增加与嫌疑人的对话次数，获取更多信息');
  }
  
  if (deduction.reasoning.length < 50) {
    suggestions.push('详细阐述你的推理过程，展示逻辑思路');
  }
  
  if (discoveredClues.length < 3) {
    suggestions.push('仔细观察，努力发现更多线索');
  }
  
  // 基于历史表现的建议
  if (previousScores.length > 0) {
    const averageScore = previousScores.reduce((sum, score) => sum + score, 0) / previousScores.length;
    if (averageScore < 60) {
      suggestions.push('建议复习基础推理方法和技巧');
    }
  }
  
  // 基于已知弱项的建议
  if (weaknesses.includes('证据分析')) {
    suggestions.push('专注练习证据分类和重要性评估');
  }
  
  if (weaknesses.includes('逻辑推理')) {
    suggestions.push('加强演绎推理和归纳推理的训练');
  }
  
  return {
    success: true,
    isCorrect: false,
    totalScore: 0,
    grade: 'N/A',
    detailedScores: { accuracy: 0, evidenceUse: 0, investigation: 0, efficiency: 0 },
    feedback: '基于你的表现生成的个性化改进建议',
    strengths: [],
    improvements: [],
    suggestions,
    learningPlan: {
      focus: determineMainFocus(deduction, gameHistory, weaknesses),
      exercises: generatePracticeExercises(weaknesses),
      resources: generateLearningResources(weaknesses)
    },
    message: '改进建议生成完成'
  };
}

/**
 * 执行完整评估
 */
async function performFullEvaluation(
  deduction: any, 
  correctAnswer: any, 
  caseData: any, 
  gameHistory: any, 
  criteria: any, 
  playerProfile: any
) {
  // 执行各项评估
  const accuracyEval = await evaluateDeductionAccuracy(deduction, correctAnswer, caseData);
  const evidenceEval = await analyzeEvidenceUsage(deduction, gameHistory, caseData);
  const investigationEval = await assessInvestigationProcess(gameHistory, caseData);
  const feedbackEval = await generateDetailedFeedback(deduction, correctAnswer, gameHistory, caseData);
  const improvementEval = await suggestImprovements(deduction, gameHistory, playerProfile);
  
  // 计算权重
  const weights = {
    accuracy: criteria.accuracyWeight || 0.4,
    evidence: criteria.evidenceWeight || 0.3,
    investigation: criteria.processWeight || 0.2,
    efficiency: criteria.efficiencyWeight || 0.1
  };
  
  // 计算总分
  const totalScore = 
    accuracyEval.detailedScores.accuracy * weights.accuracy +
    evidenceEval.detailedScores.evidenceUse * weights.evidence +
    investigationEval.detailedScores.investigation * weights.investigation +
    investigationEval.detailedScores.efficiency * weights.efficiency;
  
  // 合并优点和改进点
  const allStrengths = [
    ...accuracyEval.strengths,
    ...evidenceEval.strengths,
    ...investigationEval.strengths
  ];
  
  const allImprovements = [
    ...accuracyEval.improvements,
    ...evidenceEval.improvements,
    ...investigationEval.improvements
  ];
  
  const allSuggestions = [
    ...accuracyEval.suggestions,
    ...evidenceEval.suggestions,
    ...investigationEval.suggestions,
    ...improvementEval.suggestions
  ];
  
  return {
    success: true,
    isCorrect: accuracyEval.isCorrect,
    totalScore: Math.round(totalScore),
    grade: getGradeFromScore(totalScore),
    detailedScores: {
      accuracy: accuracyEval.detailedScores.accuracy,
      evidenceUse: evidenceEval.detailedScores.evidenceUse,
      investigation: investigationEval.detailedScores.investigation,
      efficiency: investigationEval.detailedScores.efficiency
    },
    feedback: feedbackEval.feedback,
    strengths: [...new Set(allStrengths)], // 去重
    improvements: [...new Set(allImprovements)], // 去重
    suggestions: [...new Set(allSuggestions)].slice(0, 5), // 去重并限制数量
    learningPlan: improvementEval.learningPlan,
    comparison: generateComparison(totalScore, playerProfile.previousScores),
    message: '完整评估报告生成完成'
  };
}

// 辅助函数
function getGradeFromScore(score: number): string {
  if (score >= 90) return 'A';
  if (score >= 80) return 'B';
  if (score >= 70) return 'C';
  if (score >= 60) return 'D';
  return 'F';
}

function analyzeReasoningLogic(reasoning: string): boolean {
  // 简单的逻辑分析，检查是否包含推理关键词
  const logicKeywords = ['因为', '所以', '因此', '由于', '根据', '证明', '说明'];
  return logicKeywords.some(keyword => reasoning.includes(keyword));
}

function generateEvidenceSuggestions(evidenceCount: number, importantCount: number, totalClues: number): string[] {
  const suggestions = [];
  
  if (evidenceCount < 3) {
    suggestions.push('收集更多支持证据');
  }
  if (importantCount === 0) {
    suggestions.push('识别和使用重要线索');
  }
  if (evidenceCount < totalClues * 0.5) {
    suggestions.push('充分利用已发现的线索');
  }
  
  return suggestions;
}

function analyzeQuestionTypes(conversations: any[]): string[] {
  const types = new Set();
  
  conversations.forEach(conv => {
    if (conv.content.includes('在哪') || conv.content.includes('时间')) {
      types.add('alibi');
    }
    if (conv.content.includes('为什么') || conv.content.includes('动机')) {
      types.add('motive');
    }
    if (conv.content.includes('看到') || conv.content.includes('听到')) {
      types.add('evidence');
    }
  });
  
  return Array.from(types);
}

function generateInvestigationSuggestions(coverage: number, conversationCount: number, efficiency: number): string[] {
  const suggestions = [];
  
  if (coverage < 0.8) {
    suggestions.push('确保与所有嫌疑人都有对话');
  }
  if (conversationCount < 5) {
    suggestions.push('进行更深入的对话交流');
  }
  if (efficiency < 0.3) {
    suggestions.push('提高调查效率，合理分配时间');
  }
  
  return suggestions;
}

function determineMainFocus(deduction: any, gameHistory: any, weaknesses: string[]): string {
  if (weaknesses.includes('推理准确性')) {
    return '逻辑推理能力提升';
  }
  if (deduction.evidence.length < 2) {
    return '证据收集和分析';
  }
  if (gameHistory.conversationHistory.length < 3) {
    return '调查技巧和对话策略';
  }
  return '综合推理能力';
}

function generatePracticeExercises(weaknesses: string[]): string[] {
  const exercises = [];
  
  if (weaknesses.includes('逻辑推理')) {
    exercises.push('练习演绎推理题目');
    exercises.push('分析经典推理案例');
  }
  
  if (weaknesses.includes('证据分析')) {
    exercises.push('证据分类练习');
    exercises.push('线索关联分析训练');
  }
  
  exercises.push('多玩推理游戏提高实战经验');
  
  return exercises;
}

function generateLearningResources(weaknesses: string[]): string[] {
  const resources = [];
  
  resources.push('推理小说阅读');
  resources.push('逻辑思维训练书籍');
  
  if (weaknesses.includes('证据分析')) {
    resources.push('法医学基础知识');
  }
  
  return resources;
}

function generateComparison(currentScore: number, previousScores: number[] = []): any {
  if (previousScores.length === 0) {
    return {
      averageScore: currentScore,
      percentile: 50,
      improvement: 0
    };
  }
  
  const averageScore = previousScores.reduce((sum, score) => sum + score, 0) / previousScores.length;
  const improvement = currentScore - averageScore;
  
  // 简单的百分位计算
  const betterThan = previousScores.filter(score => currentScore > score).length;
  const percentile = (betterThan / previousScores.length) * 100;
  
  return {
    averageScore: Math.round(averageScore),
    percentile: Math.round(percentile),
    improvement: Math.round(improvement)
  };
}
